<?php

class UserService{
	
	public static function home($cid = 0,$pageno = 1){
		$ret = array();
		
		$user = UserAR::userDetail();
		$ret['user'] = $user;
		
		$categorys = CategoryService::userUsedCategorys(User::id());
		$ret['categorys'] = $categorys;
		
		$page = UserBookAR::listBooks($cid, $pageno, User::id());
		$ret['page'] = $page; 
		
		$ret['curr_cid'] = $cid;
		$ret['curr_cname'] = CategoryAR::getNameById($cid);
		return $ret;
	}
	
	public static function dumpBook($bookId){
		$success = true;
		$message = '转存成功';
		$userId = User::id();
		if($userId == 0){
			return array('success'=>false,'message'=>'请先登录');
		}
		if(UserBookAR::isExists($userId,$bookId)){
			return array('success'=>false,'message'=>'这本书已经转存过了');
		}
		$bookDumpInfo = BookAR::dumpInfo($bookId);
		UserBookAR::saveUserBook($userId,$bookId,$bookDumpInfo['book_name'],$bookDumpInfo['fk_category']);
		UserAR::increDiskUsedAndDiskSize($userId,$bookDumpInfo['book_size']);
		return array('success'=>true,'message'=>'转存成功');
	}
	
	public static function delBook($bookId = 0){
		UserBookAR::del($bookId,User::id());
		//BookAR::del($bookId,User::id());
		//CommentAR::delByBooId($bookId);
	}
	
    public static function whenLogin($userId = 0,$userName = 'Guest'){
        if($userId === 0){
            return 0;
        }
        //check today login
        $hasLoginToday = DiskGenAR::isLoginToday($userId);
        if($hasLoginToday){
            return 0;
        }
        $genSize = DiskGenAR::forLogin($userId,$userName);
        UserAR::increDiskSize($userId,$genSize*1024*1024);
        return $genSize;
    }
    
    public static function topNewDiskGen($limit = 5){
    	return DiskGenAR::topNew($limit);
    }
	
    public static function allUserCount(){
        return UserAR::model()->count();
    }

    public static function usernameExists($username = ''){
        $cnt = UserAR::model()->count('user_name=?',array($username));
        return $cnt>0;
    }

    public static function emailExists($email = ''){
        $cnt = UserAR::model()->count('email=?',array($email));
        return $cnt>0;
    }

    public static function reg($username='',$password='',$email=''){
        try{
            UserAR::saveUser($username,$password,$email);
            return true;
        }catch(Exception $e){
            return false;
        }
    }
}
